--�����
--targetNode{cc.Node} ���Ŀ��
--scale {number} ���ű���
--delegate {cc.Node} ����Ŀ��

--[[
Click.new(Sprite):clickHandler(function()
	mgrs.log:printNotice("xxxxxxxxxxxxxxxxxxxxxxx");
end)
]]

local Click = class("Click");
function Click:ctor(args)
	self._targetNode = args.targetNode;
	self._scale = args.scale or 0.9;
	self._delegate = args.delegate or args.targetNode;
	self._clickHandler = nil;
	self._clickHandlerParam = {}
	self._touchInTarget = true;
	self:setTouchEnabled(true);
	self:setTouchEvent();
    self.swallowEnabled = true;
end

function Click:setTouchEvent()
    local oldScaleX = self._targetNode:getScaleX();
	local oldScaleY = self._targetNode:getScaleY();
    self._targetNode:addNodeEventListener(cc.NODE_TOUCH_EVENT,function(event)
        self._targetNode:setTouchSwallowEnabled(self.swallowEnabled);
		if event.name == "began" then
			self._delegate:setScale(oldScaleX * self._scale,oldScaleY * self._scale);
            self._touchInTarget = true;
			return true;
		elseif event.name == "ended" then
			self._delegate:setScale(oldScaleX,oldScaleY);
			if self._touchInTarget and self._clickHandler then
				self._clickHandler(self._clickHandlerParam);
			end
		elseif event.name == "moved" then
			local convertPort = self._targetNode:getParent():convertToNodeSpace(cc.p(event.x,event.y));
            local boundBox = self._targetNode:getBoundingBox();
            if cc.rectContainsPoint(boundBox,convertPort) then
                self._delegate:setScale(oldScaleX * self._scale,oldScaleY * self._scale);
                self._touchInTarget = true;
            else
                self._delegate:setScale(oldScaleX,oldScaleY);
                self._touchInTarget = false;
            end
		elseif event.name == "cancelled" then
			self._delegate:setScale(oldScaleX,oldScaleY);
		end
	end);
end

function Click:setSwallowEnabled(swallow)
    self.swallowEnabled = swallow;
end

function Click:setTouchTarget(t)
    self._touchInTarget = t;
end

function Click:targetNode(tar)
	if tar then
		self._targetNode = tar;
		return self;
	end
	return self._targetNode;
end

function Click:clickHandler(clickHandler,param)
	if clickHandler then
		self._clickHandler = clickHandler;
		self._clickHandlerParam = param or {};
		return self;
	end
	return self._clickHandler;
end

function Click:setTouchEnabled(enable)
	self._targetNode:setTouchEnabled(enable);
end

function Click:setVisible(vi)
	self._targetNode:setVisible(vi);
end

return Click;